package com.itheima.app.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.Set;

@Component
public class UserListener {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Scheduled(cron = "0/1 * * * * *")
    public void run() {
        //查询被冻结的用户id
        Jedis jedis = new Jedis ("192.168.136.160", 6379);
        jedis.select (1);
        Set<String> keys = jedis.keys (ConstantUtil.FREEZE_USER + "*");
        if (CollectionUtil.isNotEmpty (keys)) {
            //遍历所有的用户
            for (String key : keys) {
                //获取token所需要的手机号
                String phone = key.replaceAll (ConstantUtil.FREEZE_USER, "");

                //遍历所有的UserToken
                jedis = new Jedis ("192.168.136.160", 6379);
                jedis.select (0);
                Set<String> keys1 = jedis.keys (ConstantUtil.USER_TOKEN + "*");
                if (CollectionUtil.isNotEmpty (keys1)) {
                    for (String UserToken : keys1) {
                        String token = UserToken.replace (ConstantUtil.USER_TOKEN, "");
                        //System.out.println (token);
                        Map parseToken = JwtUtil.parseToken (token);
                        User user = BeanUtil.mapToBean (parseToken, User.class, true);
                        if (StrUtil.equals (phone, user.getPhone ())) {
                            jedis.del (UserToken);
                        }
                    }
                }


            }
        }
    }
}
